<template>
  <div id="item-bank" class="jx-content">
    <!-- 导入试题弹出框 -->
    <!-- <el-dialog class="dialog-import-questions" title="导入试题" :visible.sync="dialogImportQuestions" width="30%">
      <div class="dialog-content">
        <el-radio v-model="dialogImportQuestionsRadio" label="1">题库中导入</el-radio>
        <el-radio v-model="dialogImportQuestionsRadio" label="2">Excel导入</el-radio>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button class="button-style" @click="dialogImportQuestionsSubmit();dialogImportQuestions = false">确 定</el-button>
        <el-button class="button-style" @click="dialogImportQuestions = false">取 消</el-button>
        <br>
      </span>
    </el-dialog> -->

    <!-- 删除提示框 -->
    <el-dialog :close-on-click-modal="false" class="dialog-import-questions" title="提示" :visible.sync="dialogDel" width="30%">
      <div class="dialog-content">
        <span class="fs16">是否确认删除</span>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button class="button-style" @click="dialogDel = false">取 消</el-button>
        <el-button class="button-style" @click="delQuestion();dialogDel = false">确 定</el-button>
        <br>
      </span>
    </el-dialog>
    <!-- 预览弹出框 -->
    <el-dialog :close-on-click-modal="false" width="850" class="dialog-questions" title="试题预览" :visible.sync="dialogQuestion">
      <div class="dialog-content markdown-body">
        <div class="question-title" v-html="rowData.content"></div>
        <div v-if="rowData.questionType === 1" v-for="(item,index) in rowData.answer" :key="index" class="question-chose">
          <span>{{ answerChose[index] }}：</span>
          <span class="question-flex" v-html="item.content"></span>
        </div>
        <div class="question-answer">答案：
          <span v-if="rowData.questionType === 3" class="chose" style="font-family:'黑体';font-size:16px;" v-html="answerTrue"></span>
          <span v-else class="chose" v-html="answerTrue"></span>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button class="button-style" @click="dialogQuestion = false">确 定</el-button>
      </span>
    </el-dialog>
    <div class="search-box fl">
      <el-form :inline="true" ref="searchForm" :model="searchForm">
        <!-- <el-form-item label="关键词">
          <el-input v-model="searchForm.keyWord"></el-input>
        </el-form-item> -->
        <el-form-item label="章节">
          <el-select :clearable="true" v-model="searchForm.chapterId" placeholder="请选择" @change="getchapterModel">
            <el-option v-for="(item,index) in chapterList" :key="index" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="题目类型">
          <el-select :clearable="true" v-model="questionTypeMessage" placeholder="请选择" @change="getTopicModel">
            <el-option v-for="(item,index) in questionTypeList" :key="index" :label="item.message" :value="item.type"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <div class="button-style" @click="getQuestionList">搜 索</div>
        </el-form-item>
      </el-form>
    </div>
    <div class="btn-group fr" style="padding:0;">
      <el-form :inline="true">
        <el-form-item>
          <div class="button-style" @click="delQuestion">批量删除</div>
        </el-form-item>
        <el-form-item>
          <router-link class="button-style" to="AddChoiceQuestion">添加试题</router-link>
        </el-form-item>
        <el-form-item>
          <!-- 导入试题 -->
          <el-upload ref="upload" class="upload-demo" :action="'/tes/course/' + $localstorage.getLocalStorage('setCourseId')+ '/businessType/1/question-repository/import-from-excel'" :multiple="false" :show-file-list="false" :on-success="uploadSuccess" :on-error="uploadError" :on-progress="uploadProgress">
            <div class="button-style">导入试题</div>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <a :href="'/tes/course/'+ $localstorage.getLocalStorage('setCourseId')+ '/businessType/1/question-repository/model'" target="_blank">Excel模板下载</a>
        </el-form-item>
      </el-form>
    </div>
    <el-table :data="questionList" style="width: 100%" @selection-change="delChoseList">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="content" label="试题题目">
        <template slot-scope="scope">
          <div :title="delHTMLLabel(scope.row.content)" style="text-align:left;" class="question-content-timu beyond-hiding" v-html="delHTMLLabel(scope.row.content)"></div>
        </template>
      </el-table-column>
      <el-table-column prop="questionTypeMessage" label="题目类型 :" width="180"></el-table-column>
      <el-table-column prop="chapterName" label="章节"></el-table-column>
      <el-table-column prop="questionOrigin" label="来源"></el-table-column>
      <el-table-column fixed="right" label="操作" width="200">
        <template slot-scope="scope">
          <el-button @click="editQuestion(scope.row)" type="text" size="small">修改</el-button>
          <el-button @click="dialogQuestionShow(scope.row)" type="text" size="small">预览</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pager.pageNum" :page-size="pager.pageSize" :total="pager.total" layout="total, prev, pager, next, jumper"></el-pagination>
  </div>
</template>
<script>
import axios from "axios";
import $ from "jquery";
export default {
  data() {
    return {
      //删除提示框
      dialogDel: false,
      id: "",
      //导入试题弹出框
      dialogImportQuestions: false,
      dialogImportQuestionsRadio: "1",
      //试题预览
      dialogQuestion: false,
      searchForm: {
        //当前页
        pageNum: 1,
        //每页显示条数
        //pageSize:10,
        //关键词
        keyWord: "",
        //章节id
        chapterId: "",
        //题型序号
        questionType: 0
      },
      //题目类型名称
      questionTypeMessage: "",
      //题目类型数组
      questionTypeList: [],
      //章节数组
      chapterList: [],
      //table列表
      questionList: [],
      //列表分页
      pager: {
        pageNum: 0, //当前页码
        pageSize: 10, //页面大小
        pages: 0, //总记录条数
        total: 0 //总页码数
      },
      //table弹出层
      rowData: "",
      //试题答案选项
      answerChose: ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"],
      //试题正确答案
      answerTrue: "",
      //删除试题id数组
      delQuestionList: []
    };
  },
  mounted() {
    this.id = this.$localstorage.getLocalStorage("setCourseId");
    this.init();
    this.reGetChapter();
    //INTERNET_ADMIN
    console.log(this.$store.state.user.roles[0],1234);
  },
  methods: {
    init() {
      this.getQuestionList();
      this.getTopicSelected();
    },
    delHTMLLabel(str) {
      let reg = /<[^>]*>|<\/[^>]*>/gm;
      let result = str.replace(reg, "");
      return result;
    },
    reGetChapter() {
      let self = this;
      self.$http
        .get(
          "/tes/course/" +
            this.$localstorage.getLocalStorage("setCourseId") +
            "/chapter/list/owner"
        )
        .then(response => {
          let res = response.data;
          if (res.code == "200") {
            self.$nextTick(() => {
              self.tableData = res.data;
            });
            //已经有章节,判断导航显示
            self.$parent.mark = false;
            self.$parent.chaperFlag = false;
          } else if (res.code == "404") {
            self.tableData = "";
            //暂无章节,判断导航显隐藏
            this.$parent.mark = true;
            this.$parent.chaperFlag = false;
          }
        })
        .catch(err => {
          self.$message.error(res.message);
        });
    },
    //导入试题
    //成功
    uploadSuccess(res) {
      let that = this;
      if (res.code === 200) {
        that.$message.success("文件上传成功");
        that.getQuestionList();
      } else {
        that.$message.error(res.message);
      }
    },
    //失败
    uploadError() {
      this.$message.error(res.message);
    },
    //上传中
    uploadProgress() {
      this.$message("文件上传中...");
    },

    //导入试题弹出关闭
    dialogImportQuestionsClose() {},
    //导入试题弹出确定
    dialogImportQuestionsSubmit() {
      if (this.dialogImportQuestionsRadio == 1) {
        this.$router.push({
          path: "ItemBankImport"
        });
      } else {
        this.$router.push({
          path: "ExcelImport"
        });
      }
    },
    //删除试题
    delQuestion() {
      var that = this;
      if (!that.delQuestionList.length) {
        that.$message({
          message: "请选择要删除的内容",
          type: "warning"
        });
        return;
      }
      that
        .$confirm("是否删除选中?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
        .then(() => {
          axios
            .delete(
              "/tes/course/" +
                this.$localstorage.getLocalStorage("setCourseId") +
                "/businessType/1/question-repository/question",
              {
                data: that.delQuestionList
              }
            )
            .then(function(res) {
              console.log("成功1");
              console.log(res, 112233);
              if (res.status === 200) {
                if (res.data.code === 200) {
                  that.$message({
                    message: "删除成功",
                    type: "success"
                  });
                  that.getQuestionList();
                }
              }
            })
            .catch(function(err) {
              if (err.response) {
                console.log(err.response);
              }
            });
        })
        .catch(() => {});
    },
    //选中checkbox
    delChoseList(val) {
      var that = this;
      that.delQuestionList = [];
      $.each(val, function(i, d) {
        that.delQuestionList.push(d.id);
      });
      //console.log(that.delQuestionList);
    },
    //修改题目
    editQuestion(row) {
      //1选择 addChoiceQuestion
      //2判断 addJudge
      //3填空 addFillInTheBlanks
      //4简答 AddShortAnswerQuestions
      //5编程 addChoiceQuestion
      //6实验 AddExperimental
      let val = row.questionType;
      switch (val) {
        case 1:
          this.$router.push({
            path: "addChoiceQuestion",
            query: {
              rowId: row.id
            }
          });
          break;
        case 2:
          this.$router.push({
            path: "addJudge",
            query: {
              rowId: row.id
            }
          });
          break;
        case 3:
          this.$router.push({
            path: "addFillInTheBlanks",
            query: {
              rowId: row.id
            }
          });
          break;
        case 4:
          this.$router.push({
            path: "AddShortAnswerQuestions",
            query: {
              rowId: row.id
            }
          });
          break;
        case 5:
          this.$router.push({
            path: "addJudge",
            query: {
              rowId: row.id
            }
          });
          break;
        case 6:
          this.$router.push({
            path: "addExperimental",
            query: {
              rowId: row.id
            }
          });
          break;
        default:
          console.log(1234);
      }
      // this.$router.push(
      //   { path: "/MyCourses/Examination/AddChoice",
      //     name: 'AddQuestionLayout',
      //     params: {
      //       rowData: row
      //     }
      //   });
      // console.log(row);
    },
    //点击预览按钮
    dialogQuestionShow(row) {
      this.dialogQuestion = true;
      console.log(row);
      this.rowData = row;
      //添加答案

      let answer = row.answer;
      this.answerTrue = "";
      //选择题
      if (row.questionType === 1) {
        //遍历找出正确答案选项
        for (let x in answer) {
          console.log(answer[x].isCorrect);
          if (answer[x].isCorrect) {
            this.answerTrue += this.answerChose[x];
          }
        }
      }
      //判断题
      if (row.questionType === 2) {
        if (answer[0].isCorrect) {
          this.answerTrue = "正确";
        } else {
          this.answerTrue = "错误";
        }
      }
      //填空题,简答，实验
      if (
        row.questionType === 3 ||
        row.questionType === 4 ||
        row.questionType === 6
      ) {
        this.answerTrue = answer[0].content;
      }
    },
    //获取题目类型
    getTopicModel(val) {
      this.searchForm.questionType = val;
    },
    //获取章节
    getchapterModel(val) {
      this.searchForm.chapterId = val;
    },
    handleSizeChange() {},
    //翻页
    handleCurrentChange(val) {
      this.searchForm.pageNum = val;
      this.getQuestionList();
    },
    //获取题目列表
    getQuestionList() {
      var that = this;
      axios
        .get(
          "/tes/course/" +
            this.$localstorage.getLocalStorage("setCourseId") +
            "/businessType/1/question-repository/question",
          {
            params: that.searchForm
          }
        )
        .then(function(res) {
          console.log("成功1");
          console.log(res);
          if (res.status === 200) {
            if (res.data.code === 200) {
              let questionList = res.data.data.content;
              let pager = res.data.data;
              //填空题替换(+)为（）
              $.each(questionList, function(i, d) {
                if (d.questionType === 3) {
                  let str = d.content;
                  var result = str.replace(/\(\+\)/g, "（）"); //把(+)替换成()
                  d.content = result;
                }
              });
              //列表赋值
              that.questionList = questionList;
              //分页赋值
              that.pager.pageNum = pager.pageNum; //当前页码
              that.pager.pageSize = pager.pageSize; //页面大小
              that.pager.pages = pager.pages; //总记录条数
              that.pager.total = pager.total; //总页码数
              console.log(pager, 666);
            }
          }
        })
        .catch(function(err) {
          if (err.response) {
            console.log(err.response);
          }
        });
    },
    //获取题目类型和章节下拉
    getTopicSelected() {
      var that = this;
      axios
        .get(
          "/tes/course/" +
            this.$localstorage.getLocalStorage("setCourseId") +
            "/businessType/1/question-repository/dropdown-list"
        )
        .then(function(res) {
          console.log("成功");
          console.log(res);
          if (res.status === 200) {
            if (res.data.code === 200) {
              console.log(res.message);
              //赋值题目类型
              let questionTypeList = res.data.data.questionTypeList;
              that.questionTypeList = questionTypeList;
              //赋值章节列表
              let chapterList = res.data.data.chapterList;
              console.log(chapterList, 111);
              that.chapterList = chapterList;
            }
          }
        })
        .catch(function(err) {
          if (err.response) {
            console.log(err.response);
          }
        });
    }
  }
};
</script>
<style lang="scss" scoped>
    @import "../../../styles/img-init";
</style>
<style lang="scss">
@import "../../../styles/layout/color_variables";

</style>
